package com.mijie.homi.admin.web.topic;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mijie.core.ApplicationProperties;
import com.mijie.core.Paging;
import com.mijie.homi.admin.domain.topic.Topic;
import com.mijie.homi.admin.domain.topic.TopicOptions;
import com.mijie.homi.admin.service.mood.MoodInfoService;
import com.mijie.homi.admin.service.topic.TopicService;
import com.mijie.homi.admin.service.user.UserService;
import com.mijie.homi.admin.util.ServerHelper;
import com.mijie.homi.common.domain.mood.MoodInfo;
import com.mijie.homi.common.domain.topic.TopicType;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.util.FileUploadUtil;
import com.mijie.util.IOUtil;

@Controller
@RequestMapping("/topic")
public class TopicController {

	@Autowired
	private TopicService service;
	@Autowired
	private UserService userService;
	@Autowired
	private MoodInfoService moodInfoService;
	
	private Logger logger = Logger.getLogger(TopicController.class);
	
	@RequestMapping("/autoClassify")
	public @ResponseBody void autoClassify(HttpServletResponse response) throws SQLException, IOException{
		/*Connection conn = ServerHelper.getConnection();
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("select id,type from topic where type!=''");
		String typeStr = null;
		String[] typeIds = null;
		int topicId = 0;
		while(rs.next()){
			topicId = rs.getInt("id");
			typeStr = rs.getString("type");
			typeIds = typeStr.split(",");
			for(String type : typeIds){
				service.addToType(Integer.parseInt(type), topicId);
			}
		}
		stmt.close();
		logger.info("autoClassify done!");*/
	}
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	public String list(Paging<Topic> paging,Model model,HttpServletRequest request){
		paging.setPageSize(10);
		Map<String,Object> searchBundle = (Map<String, Object>) request.getAttribute("searchBundle");
		if(!searchBundle.containsKey("orderBy")) searchBundle.put("orderBy", "id");
		if(!searchBundle.containsKey("order")) searchBundle.put("order", "desc");
		service.listTopic(paging, searchBundle);
//		List<MoodInfo> list = moodInfoService.listMoodInfo();
		List<TopicType> typeList = service.listTopicType();
		
//		Map<Integer,String> moodMap = new HashMap<Integer,String>();
//		if(list!=null){
//			for(MoodInfo info : list)
//				moodMap.put(info.getId(), info.getName());
//		}
		Map<Integer,String> typeMap = new HashMap<Integer,String>();
		if(typeList!=null){
			for(TopicType type : typeList)
				typeMap.put(type.getId(), type.getName());
		}
		
		List<Topic> topicList =  paging.getList();
		User author = null;
		for(Topic topic : topicList){
			author = userService.getUserById(topic.getAuthor());
			if(author!=null)
				topic.setAuthorName(author.getNickName());
			else
				topic.setAuthorName("未知");
		}
//		model.addAttribute("moodMap",moodMap);
		model.addAttribute("typeMap",typeMap);
		model.addAttribute("typeList", typeList);
		int numOfTopic = service.countTopic();
		int numOfTopicAuthor = service.countTopicAuthor();
		model.addAttribute("numOfTopic",numOfTopic);
		model.addAttribute("numOfTopicAuthor",numOfTopicAuthor);
		model.addAllAttributes(searchBundle);
		return "topic/list";
	}
	
	@RequestMapping("/create")
	public String create(Model model){
		List<MoodInfo> list = moodInfoService.listMoodInfo();
		model.addAttribute("moodList",list);
		List<TopicType> typeList = service.listTopicType();
		model.addAttribute("typeList",typeList);
		return "topic/create";
	}
	
	@RequestMapping("/save")
	public String save(Topic topic,HttpServletRequest request){
		topic.setCreateAt(new Date());
		int topicId = service.addTopic(topic);
		return "redirect:/topic/list.shtml";
	}
	
	@RequestMapping("/edit")
	public String edit(Model model,int id){
		Topic topic = service.getTopicById(id);
		if(topic!=null){
			model.addAttribute("topic",topic);
			List<TopicOptions> options = service.getOptions(id);
			model.addAttribute("options", options);
			
			List<MoodInfo> moodList = moodInfoService.listMoodInfo();
			model.addAttribute("moodList",moodList);
			List<TopicType> typeList = service.listTopicType();
			model.addAttribute("typeList",typeList);
			
			Map<Integer,Integer> moodIdMap = new HashMap<Integer,Integer>();
			int[] ids = topic.getMoodIds();
			if(ids!=null){
				for(Integer key : ids)
					moodIdMap.put(key, key);
			}
			model.addAttribute("moodIdMap",moodIdMap);
			
			Map<Integer,Integer> typeIdMap = new HashMap<Integer,Integer>();
			ids = topic.getTypeIds();
			if(ids!=null){
				for(Integer key : ids)
					typeIdMap.put(key, key);
			}
			model.addAttribute("typeIdMap",typeIdMap);
			
			
		}
		
		return "topic/edit";
	}
	
	@RequestMapping("/update")
	public @ResponseBody void  update(Topic topic) throws UnsupportedEncodingException{
		service.updateTopic(topic);
	}
	
	@RequestMapping("/verifyView")
	public String  verifyView(int id,int pass,Model model) throws IOException{
		Topic topic = service.getTopicById(id);
		List<TopicOptions> options =  service.getOptions(id);
		model.addAttribute("pass", pass);
		model.addAttribute("topic", topic);
		model.addAttribute("options", options);
		return "/topic/verifyView";
	}
	@RequestMapping("/verify/pass_all")
	public @ResponseBody void verifyPassAll(int[] ids,HttpServletResponse response) throws IOException {
		try {
			service.passAll(ids);
			IOUtil.write(response, "succ");
		} catch (IOException e) {
			IOUtil.write(response, "error");
			logger.error(e.getMessage(), e);
		}
	}
	
	@RequestMapping("/verify")
	public @ResponseBody void verify(int id,int pass,String reason,HttpServletResponse response) throws IOException {
		if(reason==null){
			if(pass==0) reason="";
		}
		try {
			service.verify(id, pass ,reason);
			IOUtil.write(response, "succ");
		} catch (IOException e) {
			IOUtil.write(response, "error");
			logger.error(e.getMessage(), e);
		}
	}
	
	@RequestMapping("/updateIsTop")
	public @ResponseBody void updateIsTop(int[] ids,int isTop){
		service.updateIsTopByIds(ids, isTop);
	}
	
	@RequestMapping("/updateDisplay")
	public @ResponseBody void updateDisplay(int id,int display){
		service.updateDisplayState(id, display);
	}
	
	
	@RequestMapping("/markDelete")
	public String markDelete(int[] ids) throws IOException{
		service.markDelete(ids);
		return "redirect:/topic/list.shtml";
	}
	
	@RequestMapping("/listOption")
	public String listOption(Model model,int topicId){
		model.addAttribute("list", service.getOptions(topicId));
		return "/topic/listOption";
	}
	
	@RequestMapping("/type/list")
	public String listType(Model model){
		List<TopicType> list = service.listTopicType();
		for(TopicType type : list){
			if(type.getImage()!=null && !type.getImage().isEmpty())
				type.setImage(ApplicationProperties.get("resource.url")+type.getImage());
			if(type.getIcon()!=null && !type.getIcon().isEmpty())
				type.setIcon(ApplicationProperties.get("resource.url")+type.getIcon());
		}
		model.addAttribute("list", list);
		return "/topic/type/list";
	}
	
	@RequestMapping("/type/create")
	public String createType() throws SQLException{
		return "/topic/type/create";
	}
	
	@RequestMapping("/type/save")
	public @ResponseBody void saveType(TopicType type,HttpServletRequest request) throws SQLException{
		type.setImage("");
		type.setIcon("");
		if(request instanceof MultipartHttpServletRequest){
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String resPath = ApplicationProperties.get("resource.path");
			String imageHome = ApplicationProperties.get("image.home");
			String uploadedFileName = null;
			MultipartFile file  =  multipartRequest.getFile("imageFile"); 
			try{
				if(file!= null && FileUploadUtil.validate(file, "jpg","jpeg","png","gif")){
					uploadedFileName = FileUploadUtil.upload(file, resPath+imageHome);
					if(uploadedFileName!=null){
						type.setImage(imageHome+uploadedFileName);
					}
				}
				file  =  multipartRequest.getFile("iconFile"); 
				if(file!= null && FileUploadUtil.validate(file, "jpg","jpeg","png","gif")){
					uploadedFileName = FileUploadUtil.upload(file, resPath+imageHome);
					if(uploadedFileName!=null){
						type.setIcon(imageHome+uploadedFileName);
					}
				}
			}catch(Exception e){
				logger.error(e.getMessage(), e);
			}
		}
		
		service.addTopicType(type);
		if(type.getId()>0){
			Connection conn = ServerHelper.getConnection();
			Statement stmt = conn.createStatement();
			stmt.execute("create table "+HomiUtil.getTopicInTypeTableName(type.getId())+"(topicId int(11) not null default 0 primary key)ENGINE=Innodb DEFAULT CHARSET=utf8");
			stmt.close();
		}
	}
	
	@RequestMapping("/type/edit")
	public String editType(int id,Model model){
		model.addAttribute("type", service.getTopicType(id));
		return "/topic/type/edit";
	}
	
	@RequestMapping("/type/update")
	public @ResponseBody void updateType(TopicType type,HttpServletRequest request){
		if(request instanceof MultipartHttpServletRequest){
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String resPath = ApplicationProperties.get("resource.path");
			String imageHome = ApplicationProperties.get("image.home");
			String uploadedFileName = null;
			MultipartFile file  =  multipartRequest.getFile("imageFile"); 
			try{
				if(file!= null && FileUploadUtil.validate(file, "jpg","jpeg","png","gif")){
					uploadedFileName = FileUploadUtil.upload(file, resPath+imageHome);
					if(uploadedFileName!=null){
						type.setImage(imageHome+uploadedFileName);
					}
				}
				
				file  =  multipartRequest.getFile("iconFile"); 
				if(file!= null && FileUploadUtil.validate(file, "jpg","jpeg","png","gif")){
					uploadedFileName = FileUploadUtil.upload(file, resPath+imageHome);
					if(uploadedFileName!=null){
						type.setIcon(imageHome+uploadedFileName);
					}
				}
			}catch(Exception e){
				logger.error(e.getMessage(), e);
			}
		}
		service.updateTopicType(type);
	}
}
